#-*-coding: utf-8-*-

# Version: 0.1
# Author: Don Li <iedon@126.com>
# License: Copyright(c) 2017 Don.Li
# Summary:

from log                  import log
from aiohttp.web          import Response, json_response
from services.dispatcher  import dispatcher
from services.prgpool     import BrokenProcessPool

import asyncio
import aiohttp_jinja2

@aiohttp_jinja2.template("index.tpl")
def index(request):
    return {'node_name': 'localhost', 'nodes': enumerate(['localhost']), 'node_url': 'http://127.0.0.1:9001'}

async def calc(request):
    post  = await request.post()
    error = { 'errno': 1, 'errinfo': 'unknown error' }
    data  = None

    params  = 'word', 'fault'
    param   = ''
    req     = {}

    try:
        for param in params:
            req[param] = post[param]
    except Exception as e:
        error['errno']   = 3
        error['errinfo'] = 'missing param: {0}'.format(param)
    else:
        try:
            task             = await dispatcher.calc(req)
            data             = { 'params': task.params, 'result': task.result }
            error['errno']   = 0
            error['errinfo'] = ''
        except BrokenProcessPool:
            log.error('worker broken. request: {0}, from: {1}'.format(req, request.transport.get_extra_info('peername')))

            error['errno']   = 4
            error['errinfo'] = 'internal error'
        except asyncio.TimeoutError:
            log.error('timeout. request: {0}, from: {1}'.format(req, request.transport.get_extra_info('peername')))

            error['errno']   = 2
            error['errinfo'] = 'timeout'
        except Exception as e:
            log.error('uncatch exception. request: {0}, from: {1}, detail: {2}'.format(req, request.transport.get_extra_info('peername'), e))
            error['errno']   = 10
            error['errinfo'] = 'internal error'

    return json_response(dict(error = error, data = data))
